<template>
  <el-form
    ref="registerFormRef"
    :model="registerForm"
    status-icon
    :rules="registerFormRules"
    label-width="120px"
    class="register-form"
  >
    <h1><span>用户注册</span></h1>

    <el-form-item label="用户名" prop="username">
      <el-input
        class="e-input"
        v-model="registerForm.username"
        type="text"
        autocomplete="off"
        :prefix-icon="User"
      />
    </el-form-item>

    <el-form-item label="密码" prop="password">
      <el-input
        class="e-input"
        v-model="registerForm.password"
        :type="isHide1 ? 'password' : 'text'"
        autocomplete="off"
        :prefix-icon="Lock"
      >
        <template #suffix>
          <el-icon class="hide-button" @click="isHide1 = !isHide1">
            <Hide v-if="isHide1"></Hide>
            <View v-else></View>
          </el-icon>
        </template>
      </el-input>
    </el-form-item>

    <el-form-item label="确认密码" prop="checkPass">
      <el-input
        class="e-input"
        v-model="registerForm.checkPass"
        :type="isHide2 ? 'password' : 'text'"
        autocomplete="off"
        :prefix-icon="Lock"
      >
        <template #suffix>
          <el-icon class="hide-button" @click="isHide2 = !isHide2">
            <Hide v-if="isHide2"></Hide>
            <View v-else></View>
          </el-icon>
        </template>
      </el-input>
    </el-form-item>

    <el-form-item>
      <el-button
        id="register-button"
        type="primary"
        @click="submitForm(<FormInstance>registerFormRef)"
        :loading="isLoading"
      >
        注册
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue"
import { Lock, User, View, Hide } from "@element-plus/icons-vue"
import type { FormInstance } from "element-plus"
import { useLoginStore } from "@/store/loginStore"
import { ElMessage } from "element-plus"

const loginStore = useLoginStore()

const registerFormRef = ref<FormInstance>()

const registerForm = reactive({
  username: "",
  password: "",
  checkPass: ""
})

//切换回登录面板
const emits = defineEmits(["switch-login"])

//隐藏密码
const isHide1 = ref<boolean>(true)
const isHide2 = ref<boolean>(true)

//按钮加载状态
const isLoading = ref<boolean>(false)

//提交表单
function submitForm(form: FormInstance) {
  form.validate((valid) => {
    if (valid) {
      isLoading.value = true
      setTimeout(async () => {
        try {
          await loginStore.requestRegister({
            username: registerForm.username.trim(),
            password: registerForm.password
          })
          ElMessage.success("注册成功，请登录")
          registerFormRef.value?.resetFields()
          emits("switch-login")
        } catch (error: any) {
          ElMessage.error(error.msg)
        } finally {
          isLoading.value = false
        }
      })
    } else {
      return false
    }
  })
}

//校验用户名
function validateUsername(rule: any, value: string, callback: any) {
  if (value === "" || /^\s*$/.test(value)) {
    callback(new Error("请输入用户名"))
  } else if (/\S\s\S/.test(value)) {
    callback(new Error("用户名中间不能包含空格"))
  } else {
    callback()
  }
}

//校验第一个密码
function validatePassword(rule: any, value: string, callback: any) {
  if (registerFormRef.value) {
    registerFormRef.value.validateField("checkPass", (isValid: boolean) => {})
  }
  if (value === "" || /^\s*$/.test(value)) {
    callback(new Error("请输入密码"))
  } else if (value.includes(" ")) {
    callback(new Error("密码不能包含空格"))
  } else {
    callback()
  }
}

//校验第二个密码
function validateCheckPass(rule: any, value: string, callback: any) {
  if (value === "" || /^\s*$/.test(value)) {
    callback(new Error("请输入密码"))
  } else if (value.includes(" ")) {
    callback(new Error("密码不能包含空格"))
  } else if (value !== registerForm.password) {
    callback(new Error("密码输入不一致"))
  } else {
    callback()
  }
}

const registerFormRules = reactive({
  username: [{ validator: validateUsername, trigger: "blur" }],
  password: [{ validator: validatePassword, trigger: "blur" }],
  checkPass: [{ validator: validateCheckPass, trigger: "blur" }]
})
</script>

<style lang="scss" scoped>
.register-form {
  margin-left: 150px;
  border: 1px solid rgba(205, 198, 198, 0.957);
  border-radius: 10px;
  padding-top: 30px;
  padding-left: 0;
  width: 450px;
  box-shadow: 0px 5px 10px #cccc;
  height: 250 px;
  vertical-align: middle;
  text-align: center;
  font-weight: bolder;

  span {
    user-select: none;
    position: relative;
    bottom: 10px;
    left: 35px;
  }
}

:deep(.el-form-item__label) {
  user-select: none;
}

.e-input {
  width: 300px;
}

#register-button {
  width: 300px;
}

.hide-button {
  cursor: pointer;
}
</style>
